# -*- coding: utf-8 -*-

"""
* Copyright (C) 2016 GridSafe, Inc.
"""
import pytz
import calendar
from datetime import datetime
from datetime import timedelta
from django.conf import settings
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required


class LoginRequiredMixin(object):
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, *kwargs)


class UserMixin(object):
    def __init__(self):
        self.income_cur_objs = self.get_cur_month_obj('Income')
        self.pay_cur_objs = self.get_cur_month_obj('Pay')
        pass

    def get_day_interval(self, date_start=None):
        """获取当前月份第一天,下月第一天"""
        if date_start is None:
            date_start = datetime.now(tz=pytz.timezone(settings.TIME_ZONE)).replace(day=1, hour=0, minute=0, second=0,
                                                                                    microsecond=0)
        _, days_in_month = calendar.monthrange(date_start.year, date_start.month)
        date_end = date_start + timedelta(days=days_in_month)
        return (date_start, date_end)

    def get_cur_month_obj(self, model_name):
        from apps.wallet.models.statistic import IncomeTable
        from apps.wallet.models.statistic import ExpenseTable

        date_start, date_end = self.get_day_interval()
        if model_name == 'Income':
            cur_mon_obj = IncomeTable.objects.filter(created_datetime__range=(date_start, date_end),
                                                     user_id=self.id).values_list('money')
        else:
            cur_mon_obj = ExpenseTable.objects.filter(created_datetime__range=(date_start, date_end),
                                                      user_id=self.id).values_list('money')
        return cur_mon_obj

